<template>
  <!-- 采购计划 -->
  <div class="purchase_plan_list" ref="purchase">
    <div style="padding:10px;margin:10px;background:#fff">
      <input type="file" ref="upload" accept=".xls,.xlsx" @change="readExcel" class="outputlist_upload">
      <el-select v-model="searchForm.proId" style="margin-right: 6px" filterable clearable placeholder="请选择项目" value-key="name">
        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id" />
      </el-select>
      <el-button style="margin-right: 6px" type="primary" icon="el-icon-search" size="small" @click="toSearch">查询</el-button>
    </div>
    <el-card shadow="never" style="margin:10px;background:#fff">
      <div slot="header" class="index-md-title">
        <span>采购计划</span>
        <el-button :disabled="table.selected.length>0?false:true" round style="margin-right: 6px" type="danger" @click="toDeleteItems" icon="el-icon-delete" size="small">批量删除</el-button>
        <el-button :disabled="table.selected.length>0?false:true" round style="margin-right: 6px" @click="handleAddInquiry" type="primary" icon="el-icon-document" size="small">发往询价</el-button>
        <el-button style="margin-right: 6px" type="primary" round size="small" @click="toAddItems">新增采购项</el-button>
        <el-button @click="importHandle" round type="success" size="small"><a-icon type="file-excel" style="font-size: 12px;margin-right: 5px"/>excel导入</el-button>
        <el-button round type="primary" icon="el-icon-setting" size="small" @click="templateSelected">设置解析模板</el-button>
      </div>
      <a-table
        size="small"
        :rowKey="record => record.id"
        :loading="table.loading"
        :data-source="table.data"
        :pagination="table.pagination"
        :row-selection="{ selectedRowKeys: table.selected, onChange: onSelectChange, selections: [{
            key: 'all-data',
            text: '全选',
            onSelect: () => {this.table.selected =  table.data.map(i=>{return i.id});},}],
            getCheckboxProps: record => ({props: {disabled: record.isInquiry == 1}})}"
        :customRow="rowClick"
        :scroll="table.data.length > 0 ?{ x: 900}:{}">
        <a-table-column :width="70" align="center" key="isInquiry" title="状态" data-index="isInquiry">
          <template slot-scope="text">
            <el-tag :type="text == 1 ? 'success':'info'">{{ text == 1 ? '已发询价':'未发询价' }}</el-tag>
          </template>
        </a-table-column>
        <a-table-column :width="120" align="center" ellipsis="true" key="item" title="设备名称" data-index="item" />
        <a-table-column v-if="item.key != 'inquiryRemark' && item.key != 'name' && item.key != 'realBrand'"
                        v-for="item in currentTemplate.tableColumn" ellipsis="true"
                        :width="item.width" :align="item.align" :key="item.key" :title="item.title" :dataIndex="item.dataIndex" />
        <a-table-column :width="250" align="center" flex="right" key="action" title="操作" fixed="right">
          <template slot-scope="text, record">
            <el-button v-if="record.isInquiry == 0" @click.stop="poolChoose(record)" type="success" icon="el-icon-star-on" size="mini" style="padding: 7px 10px;background: #faad14;border-color:#faad14">产品池</el-button>
            <el-button v-if="record.isInquiry == 0" @click.stop="splitPurchaseItem(record)" type="info" size="mini" >拆分</el-button>
            <el-button @click.stop="editPurchaseItem(record)" size="mini" type="success" >修改</el-button>
          </template>
        </a-table-column>
      </a-table>
    </el-card>
    <el-card shadow="never" style="margin:10px;background:#fff">
      <div slot="header" class="index-md-title">
        <span>采购供应商</span>
        <span v-if="currentItem!='' && currentItem">【{{currentItem}}】</span>
      </div>
      <a-table
        size="small"
        :pagination="false"
        ref="purchaseSuppliers"
        :rowKey="record => record.id"
        :loading="purchaseSupplierLoading"
        :data-source="purchaseSuppliers"
        :scroll="purchaseSuppliers.length > 0 ?{ x: 1200}:{}">
        >
        <a-table-column :width="150" align="center" fixed="left" key="supplier" ellipsis="true" title="供应商" data-index="supplier" />
        <a-table-column :width="100" align="center" fixed="left" key="brand" ellipsis="true" title="品牌" data-index="brand" />
        <a-table-column :width="150" align="center" key="model" title="型号" ellipsis="true" data-index="model" />
        <a-table-column :width="150" align="center" key="params" title="技术参数" ellipsis="true" data-index="params" />
        <a-table-column :width="70" align="center" key="price" title="单价" ellipsis="true" data-index="price" />
        <a-table-column :width="80" align="center" key="totalPrice" ellipsis="true" title="总价" >
          <template slot-scope="text, record">
            {{Number(record.price * currentNum).toFixed(2)}}
          </template>
        </a-table-column>
        <a-table-column :width="100" align="center" key="delivery" title="货期" data-index="delivery" />
        <a-table-column :width="100" align="center" key="warranty" title="质保期" data-index="warranty" />
        <a-table-column align="center" key="remark" title="备注" data-index="remark" />
        <a-table-column :width="60" align="center" flex="right" key="action" title="操作" fixed="right">
          <template slot-scope="text, record">
            <el-button  @click="deletePurchaseSupply(record, index)" type="danger" icon="el-icon-delete" size="mini" ></el-button>
          </template>
        </a-table-column>
      </a-table>
    </el-card>

    <!-- 产品池模态框 -->
    <el-dialog v-el-drag-dialog title="选择产品池产品" class="poolDialog" :visible.sync="poolDialog.visible">
      <el-form :model="poolDialog.form" status-icon>
        <el-row :gutter="10">
          <el-col :sm="24" :lg="12">
            <el-form-item label="采购项" label-width="80px" prop="item">{{poolDialog.form.item}}</el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="品牌" label-width="80px" prop="brand">{{poolDialog.form.brand}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="型号" label-width="80px" prop="model">{{poolDialog.form.model}}</el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="技术要求" label-width="80px" prop="params">{{poolDialog.form.params}}</el-form-item>
          </el-col>
        </el-row>
        <el-input type="text"
                  v-model="poolDialog.searchForm.name"
                  placeholder="设备名" size="small" style="max-width: 200px;"></el-input>
        <el-input type="text"
                  v-model="poolDialog.searchForm.model"
                  placeholder="型号" size="small" style="max-width: 200px;"></el-input>
        <el-button type="primary" size="small" @click="poolFind">查询</el-button>
        <div style="margin-top: 6px">
          <a-table
            size="small"
            :pagination="poolDialog.table.pagination"
            :rowKey="record => record.id"
            :loading="poolDialog.table.loading"
            :data-source="poolDialog.table.data"
            :scroll="poolDialog.table.data.length > 0 ?{ x: 600, y: 240}:{}"
            :rowSelection="{selectedRowKeys: poolDialog.table.selected, onChange: poolTableChange, type:'radio'}"
          >
            <a-table-column :width="100" align="center" key="name" title="设备名称" data-index="name" />
            <a-table-column :width="100" align="center" key="supplier" title="供应商" data-index="supplier" />
            <a-table-column :width="150" align="center" key="params" title="技术参数" data-index="params" />
            <a-table-column :width="150" align="center" key="model" title="品牌型号" data-index="model" />
            <a-table-column :width="70" align="center" key="price" title="单价" data-index="price" />
            <a-table-column :width="70" align="center" key="number" title="数量" data-index="number" />
            <a-table-column :width="100" align="center" key="delivery" title="货期" data-index="delivery" />
          </a-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="poolDialog.visible = false">取消</el-button>
        <el-button type="primary" size="small" @click="poolSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 采购项模态框 -->
    <el-dialog v-el-drag-dialog :title="itemDialog.title" class="itemDialog" :visible.sync="itemDialog.visible">
      <el-form ref="form" :rules="rules" :model="itemDialog.form" status-icon>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="采购模板" label-width="80px" prop="templateId">
              <el-select v-model="itemDialog.form.templateId" @change="aaa" :disabled="itemDialog.disabled" style="width: 100%" size="small" placeholder="请选择模板" value-key="name">
                <el-option v-for="item in excelTemplates" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="采购序号" label-width="80px" prop="sort">
              <el-input :disabled="itemDialog.form.isInquiry == 1 ? true: false" v-model="itemDialog.form.sort" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item size="mini" label="设备名称" label-width="80px" prop="item">
              <el-input v-model="itemDialog.form.item" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="单位" label-width="80px" prop="unit">
              <el-input v-model="itemDialog.form.unit" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="数量" label-width="80px" prop="number">
              <el-input v-model="itemDialog.form.number" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="品牌" label-width="80px" prop="suDelivery">
              <el-input v-model="itemDialog.form.brand" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="要求货期" label-width="80px" prop="requiredDelivery">
              <el-input v-model="itemDialog.form.requiredDelivery" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24" :lg="12">
            <el-form-item label="备注" label-width="80px" prop="suRemark">
              <el-input v-model="itemDialog.form.remark" autocomplete="off" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="currentTemplate&&currentTemplate.tableColumn&&currentTemplate.tableColumn.length>0">
          <el-divider><i class="el-icon-mobile-phone"> {{currentTemplate.name}}</i></el-divider>
          <el-row v-show="index%2 == 0" v-for="(item, index) in column" :key="item.key">
            <el-col :sm="24" :lg="12">
              <el-form-item :label="item.title" label-width="80px" :prop="item.key">
                <el-input v-model="itemDialog.form[item.key]" autocomplete="off" size="small" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item v-if="column[index+1]" :label="column[index+1].title" label-width="80px" :prop="column[index+1].key">
                <el-input v-model="itemDialog.form[column[index+1].key]" autocomplete="off" size="small" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="itemDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="itemDialog.submitLoading" size="small" @click="itemSubmit('form')">提交</el-button>
      </div>
    </el-dialog>

    <!-- 导入采购计划 -->
    <el-dialog title="导入采购计划" class="importDialog" :visible.sync="importDialog.visible">
      <el-form :model="importDialog.form" status-icon>
        <div>
          <div style="margin: 8px 0 26px 0;position: relative">
            <el-select size="small" @change="importDialogChange" :disabled="importDialog.disabled" v-model="importDialog.form.templateId" placeholder="请选择解析模板" value-key="name" style="margin:0 0 8px 1em">
              <el-option v-for="item in excelTemplates" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button @click="clickFileInput" type="primary" size="small"><a-icon type="file-excel" style="font-size: 12px;margin-right: 5px"/>excel导入</el-button>
            <input type="file" ref="upload" accept=".xls,.xlsx" @change="readExcel" class="outputlist_upload">
            <div v-if="excelRows>0" style="position: absolute;left: 0;padding: 4px 0;font-size: 12px;color: #909399">从Excel读取到
              <span style="color: #42b983">{{outputs.length}}</span>条数据
            </div>
          </div>
          <el-input
            type="textarea"
            placeholder="点击上方按钮导入或者复制excel中数据来粘贴"
            :autosize="{ minRows: 4, maxRows: 12}"
          >
          </el-input>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="importDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="importDialog.submitLoading" size="small" @click="importCommit()">提交</el-button>
      </div>
    </el-dialog>

    <!--解析模板模态框-->
    <el-dialog v-el-drag-dialog :visible.sync="templateDialog.visible" title="选择解析模板" style="width: 120%">
      <el-form v-model="templateDialog.form" status-icon>
        <el-select v-model="templateDialog.form.templateId" filterable clearable placeholder="请选择模板" value-key="name">
          <el-option v-for="item in templateDialog.dataSource" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="templateDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="templateDialog.submitLoading" size="small" @click="setAnalysisTemplate">选取</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import '@/styles/auto-style.css'
  import { getUser } from '@/utils/auth'
  import XLSX from 'xlsx'
  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import elDragDialog from '@/directive/el-drag-dialog'

  export default {
    directives: { elDragDialog },
    data() {
      var validSerialNumber = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }
        getAction(this.url.checkSerialNumberIsExists,{ projectId: this.searchForm.proId, serialNum: value })
        .then(response => {
          if (response.data > 0 && value != this.nokey) {
            callback(new Error('采购项序号已存在'))
          }else {
            callback()
          }
        })
      };
      var validTemplate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }else {
          callback()
        }
      };
      return {
        currentNum: null,
        currentItem: '',
        purchaseSuppliers: [],
        purchaseSupplierLoading: false,

        noKey: null,
        //根据itemId查询供货数据
        itemId: '',
        //产品池查询的设备名
        name: '',
        selectedRowKeysaaa: [],
        sendInquiryItem: [],
        column: [],

        //当前模板
        currentTemplate: {},
        //excel解析出来装进去的变量
        outputs: [],
        excelRows: null,

        excelTemplates: [],
        itemIds: [],
        projects: [],
        searchForm: {},
        table: {
          selected: [],
          data: [],
          loading: false,
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.table.pagination.current = item
              this.toSearch()
            },
            onShowSizeChange: (current, pageSize) => {
              this.table.pagination.pageSize = pageSize
              this.toSearch()
            }, // 改变每页数量时更新显示
          },
        },
        importDialog: {
          disabled: false,
          visible: false,
          submitLoading: false,
          form: {}
        },
        templateDialog: {
          form: {},
          loading: false,
          visible: false,
          submitLoading: false,
          dataSource: []
        },
        itemDialog: {
          form: {},
          submitLoading: false,
          visible: false,
          disabled: false
        },
        poolDialog: {
          form: {},
          searchForm: {},
          visible: false,
          submitLoading: false,
          table: {
            loading: false,
            data: [],
            selected: [],
            pagination: {
              showTotal: total => `共 ${total} 条结果`,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              current: 1,
              pageSize: 10,
              total: 0,
              onChange: (item) => {
                this.poolDialog.table.pagination.current = item
                this.loadPool()
              },
              onShowSizeChange: (current, pageSize) => {
                this.poolDialog.table.pagination.pageSize = pageSize
                this.loadPool()
              }, // 改变每页数量时更新显示
            },
          },
        },
        rules: {
          templateId: [
            { validator: validTemplate, trigger: 'blur'}
          ],
          sort: [
            { validator: validSerialNumber, trigger: 'blur'}
          ],
          item: [
            { required: true, message: '不能为空', trigger: 'blur'}
          ],
          number: [
            { required: true, message: '不能为空', trigger: 'blur'}
          ]
        },
        url: {
          setAnalysisTemplate: '/inquiry/template/setAnalysisTemplate',
          findInquiryTemplate: '/inquiry/template/findInquiryTemplate',
          findItemsByProjectId: '/purchase/purchasePlan/findItemsByProjectId',
          findAllLike: '/purchase/project/findAllLike',
          excelPurchaseItems: '/purchase/purchasePlan/excelPurchaseItems',
          deletePurchaseItems: '/purchase/purchasePlan/deletePurchaseItems',
          findPurchasingSupplierByItemId: '/purchase/purchasePlan/findPurchasingSupplierByItemId',
          insertInquiryInfo: '/purchase/purchasePlan/insertInquiryInfo',
          findHistoryPrices: '/pool/findHistoryPrices',
          insertSupplyByItem: '/purchase/purchasePlan/insertSupplyByItem',
          checkSerialNumberIsExists: '/purchase/purchasePlan/checkSerialNumberIsExists',
          saveOrUpdatePurchaseItem:'/purchase/purchasePlan/saveOrUpdatePurchaseItem'
        }
        //windowWidth: document.documentElement.clientWidth, // 屏幕实时宽度
      }
    },
    mounted() {
      /*var that = this;
      // <!--把window.onresize事件挂在到mounted函数上-->
      window.onresize = () => {
        return (() => {

          //window.fullWidth = document.documentElement.clientWidth;
          that.windowWidth = that.$refs.purchase.clientWidth ; // 宽
        })()
      };*/
    },
    created() {
      this.loadPurchasePros()
      this.loadTemplates()
    },
    methods: {




      splitPurchaseItem(row) {
        this.$prompt('请输入拆分数量', '采购项拆分', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[1-9][0-9]*([\.][0-9]{1,2})?$/,
          inputErrorMessage: '格式不正确'
        }).then(({ value }) => {
          if (value >= row.number) {
            this.$message({message: '不能大于或等于原始数量【'+row.number+'】', type: 'warning'})
            return false
          }else {
            let form = {}
            form = row
            form.operator = getUser()
            form.itemNum = value
            postActionByQueryString('/purchase/purchasePlan/insertItem', form)
            .then(resp => {
              this.$message({message: resp.message, type: 'success'})
              this.toSearch()
            })
          }
        })
      },








      async importDialogChange(){
        if (this.importDialog.form.templateId){
          this.currentTemplate.id = this.importDialog.form.templateId
          await this.loadCurrentTemplate(this.currentTemplate.id)
          this.column = this.currentTemplate.tableColumn.filter(item => item.commons == false)
        }
      },
      importHandle() {
        if (this.searchForm.proId) {
          if (this.currentTemplate.id){
            //项目存在模板则以项目模板ID  禁止选择
            this.importDialog.disabled = true
            this.importDialog.form.templateId = this.currentTemplate.id
          }else {
            //不存在则可选择
            this.importDialog.disabled = false
          }
          this.importDialog.visible = true
        }else {
          this.$message({type: 'warning', message: '请选择采购项目'})
        }
      },
      poolSubmit() {
        this.poolDialog.submitLoading = true
        if(this.poolDialog.table.selected.length === 1){
          postActionByQueryString(this.url.insertSupplyByItem, {
            poolId: this.poolDialog.table.selected, itemId: this.itemId})
          .then(resp => {
            this.$message.success(resp.message)
          }).catch(()=>{
            this.$message.error('提交失败')
          }).finally(()=>{
            this.poolDialog.visible = false
            this.poolDialog.submitLoading = false
            this.toSearchSupply()
          })
        }else {
          this.$message.error('选取有误')
        }
      },
      poolTableChange(ids, rows){
        this.poolDialog.table.selected = ids
      },
      poolFind() {
        this.name = this.poolDialog.searchForm.name
        this.loadPool()
      },
      poolChoose(row) {
        this.poolDialog.submitLoading = false
        this.poolDialog.visible = true
        this.poolDialog.form = row
        this.name = row.item
        this.itemId = row.id
        this.loadPool()
      },
      loadPool() {
        this.poolDialog.table.loading = true
        this.poolDialog.submitLoading = true
        this.poolDialog.table.selected = []
        getAction(this.url.findHistoryPrices,{name: this.name, model: this.poolDialog.searchForm.model,
          pageNum: this.poolDialog.table.pagination.current,
          pageSize: this.poolDialog.table.pagination.pageSize})
        .then(resp => {
          this.poolDialog.table.data = resp.data.records
          this.poolDialog.table.pagination.current = parseInt(resp.data.current)
          this.poolDialog.table.pagination.pageSize = parseInt(resp.data.size)
          this.poolDialog.table.pagination.total = parseInt(resp.data.total)
        }).catch(() => {
          this.$message.error('查询错误')
        }).finally(()=>{
          this.poolDialog.table.loading = false
          this.poolDialog.submitLoading = false
        })
      },
      handleAddInquiry() {
        this.$confirm('是否确定发往询价，不可撤销，请谨慎操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postActionByQueryString(this.url.insertInquiryInfo, {itemIds: this.table.selected, proId: this.searchForm.proId})
          .then(resp => {
            this.$message({ type: resp.message, message: resp.data + '条发送成功'})
          }).catch(()=>{
            this.$message.error('操作失败')
          }).finally(() => {
            this.table.selected = []
            this.toSearch()
          })
        })
      },
      toSearchSupply() {
        this.purchaseSupplierLoading = true
        getAction(this.url.findPurchasingSupplierByItemId, { id: this.itemId })
          .then( resp => {
            this.purchaseSuppliers = resp.data
          })
          .catch(() => {
            this.$message.error('查询失败')
          }).finally(()=>{
          this.purchaseSupplierLoading = false
        })
      },
      rowClick(row, index) {
        return {
          on: {
            click: () => {
              this.itemId = row.id
              this.currentItem = row.item
              this.currentNum = row.number
              this.toSearchSupply()
            }
          }
        }
      },
      loadTemplate(){
        getAction(this.url.findInquiryTemplate)
        .then(resp => {
          this.templateDialog.dataSource = resp.data
        }).catch(()=>{
          this.$message({ type :'error', message :'模板加载失败' })
        })
      },
      async templateSelected(){
        if (this.itemIds.length > 0) {
          await this.loadTemplate();
          if (this.currentTemplate.id){
            this.$set(this.templateDialog.form, 'templateId', this.currentTemplate.id)
          }
          this.templateDialog.visible = true;
        }else {
          this.$message({ type :'error', message :'无明细需设置模板' })
        }
      },
      setAnalysisTemplate(){
        postActionByQueryString(this.url.setAnalysisTemplate, {
          proId :this.searchForm.proId,
          templateId :this.templateDialog.form.templateId})
        .then(resp =>{
          this.$message({ type :'success', message :resp.message + '条解析模板设置成功' })
        }).catch(()=>{
          this.$message({ type :'error', message :'解析模板设置失败' })
        }).finally(()=>{
          this.templateDialog.visible = false
          this.templateDialog.loading = false
          this.toSearch()
        })
      },
      async aaa(){
        if (this.itemDialog.form.templateId){
          this.currentTemplate.id = this.itemDialog.form.templateId
          await this.loadCurrentTemplate(this.currentTemplate.id)
          this.column = this.currentTemplate.tableColumn.filter(item => item.commons == false)
        }
      },
      async editPurchaseItem(row){
        this.itemDialog.form = row
        this.itemDialog.title = '修改采购项'
        this.nokey = row.sort
        if (this.currentTemplate.id) {
          //项目存在模板id 禁止选择
          this.itemDialog.form.templateId = this.currentTemplate.id
          this.itemDialog.disabled = true
          await this.aaa()
        }else {
          this.$message({type: 'warning', message: '该采购计划未设置模板'})
        }
        this.itemDialog.visible = true
      },
      async toAddItems(){
        this.itemDialog.form = {}
        this.itemDialog.disabled = false
        this.itemDialog.title = '新增采购项'
        this.nokey = ''
        if(this.searchForm.proId) {
          if (this.currentTemplate.id) {
            //项目存在模板id 禁止选择
            this.itemDialog.form.templateId = this.currentTemplate.id
            await this.aaa()
            this.itemDialog.disabled = true
            this.itemDialog.visible = true
          }
        }else {
          this.$message({message: '请选择采购项目', type: 'warning'})
        }
      },
      itemSubmit(form){
        this.itemDialog.submitLoading = true
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.itemDialog.form.projectId = this.searchForm.proId
            postActionByQueryString(this.url.saveOrUpdatePurchaseItem, this.itemDialog.form)
            .then(resp => {
              this.$message({ message: resp.message, type: 'success' })
            }).catch(()=>{
              this.$message({ message: '提交失败', type: 'error' })
            }).finally(()=>{
              this.itemDialog.visible = false
              this.itemDialog.submitLoading = false
              this.itemDialog.form = {}
              this.toSearch()
            })
          }else {
            this.$message.error('验证失败')
            this.itemDialog.submitLoading = false
            return false
          }
        })
      },
      toDeleteItems() {
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.table.selected.length === 0){
            this.$message({ message: '无删除数据', type: 'warning'})
          }else {
            postActionByQueryString(this.url.deletePurchaseItems, { purchaseItemIds: this.table.selected})
            .then(resp => {
              this.$message({message: resp.data + '条数据删除成功', type: 'success'})
            }).catch(()=>{
              this.$message({message: '删除失败', type: 'error'})
            }).finally(()=>{
              this.table.selected = []
              this.toSearch()
            })
          }
        })
      },
      deletePurchaseSupply(row, index) {
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let form = {}
          form.id = row.id
          form.itemId = row.itemId
          postActionByQueryString("/purchase/purchasePlan/deletePurchaseSupply", form)
          .then(resp => {
            this.$message({message: resp.message, type: 'success'})
            this.toSearchSupply(row)
          })
        })
      },
      importCommit() {
        if (this.outputs.length > 0) {
          this.importDialog.visible = true
          this.importDialog.submitLoading = true
          postActionByJson(this.url.excelPurchaseItems, { purchaseItems: this.outputs})
          .then(resp => {
            this.$message({ type: 'success', message: resp.message})
          })
          .catch(() => {
            this.$message({ type: 'error', message: '提交失败'})
          }).finally(()=>{
            this.importDialog.visible = false
            this.importDialog.submitLoading = false
            this.toSearch()
          })
        }else {
          this.$message({ type: 'warning', message: '无数据提交'})
        }
      },
      readExcel(e) {
        const files = e.target.files;
        if(files.length<=0){//如果没有文件名
          return false;
        }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
          this.$message.error('上传格式不正确，请上传xls或者xlsx格式');
          return false;
        }
        this.excelRows = 0
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            const wsname = workbook.SheetNames[0];//取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
            this.outputs = [];//清空接收数据
            let parent = {}
            let children = []
            ws.map(item => {
              if(this.currentTemplate.id){
                if(this.currentTemplate.tree === 0) {
                  let num = Object.keys(item).length;
                  if(num>2 && item['序号']){
                    let keyArray = Object.keys(item)
                    let inquiry = {}
                    keyArray.map(key => {
                      if (this.currentTemplate.purchaseKeys[key] != undefined){
                        inquiry[this.currentTemplate.purchaseKeys[key]] = item[key]
                      }
                    })
                    inquiry['projectId'] = this.searchForm.proId
                    inquiry['templateId'] = this.currentTemplate.id
                    this.outputs.push(inquiry);
                  }else {
                    this.$message.error('解析数量为空或缺失序号')
                  }
                }else{
                  //树结构
                  let no = item['序号']+''
                  if(!no.includes('.') && Object.keys(item).length <= 2) {
                    if (parent['name']) {
                      parent['children'] = children
                      parent['projectId'] = this.searchForm.proId
                      this.outputs.push(parent)
                      parent = {}
                      children = []
                    }
                    parent['sort'] = no
                    var keys = Object.keys(item)
                    parent['name'] = item[keys[1]]
                  }else {
                    let keyArray = Object.keys(item)
                    let inquiry = {}
                    keyArray.map(key => {
                      if (this.currentTemplate.purchaseKeys[key] != undefined)
                        inquiry[this.currentTemplate.purchaseKeys[key]] = item[key]
                    })
                    inquiry['projectId'] = this.searchForm.proId
                    inquiry['operator'] = userId
                    inquiry['templateId'] = this.currentTemplate.id
                    children.push(inquiry)
                  }
                }
                this.excelRows ++
              }else {
                //无模板
                this.$message({type: 'warning', message:'请选择解析模板'})
              }
            })
            if(this.currentTemplate.tree == 1) {
              parent['children'] = children
              parent['projectId'] = this.searchForm.proId
              this.outputs.push(parent)
            }
            this.$refs.upload.value = '';
          } catch (e) {
            return false;
          }
        };
        fileReader.readAsBinaryString(files[0]);
      },
      clickFileInput(){
        if (this.searchForm.proId) {
          this.$refs.upload.dispatchEvent(new MouseEvent('click'))
        }else {
          this.$message({type: 'warning', message: '请选择采购项目'})
        }
      },
      onSelectChange(ids, rows) {
        const itemsId = []
        ids.map(item => {
          itemsId.push(item)
        })
        this.table.selected = itemsId
      },
      loadPurchasePros() {
        getAction(this.url.findAllLike)
        .then(response => {
          this.projects = response.data
        }).catch(()=>{
          this.$message.error('项目加载失败')
        })
      },
      async loadCurrentTemplate(id) {
        if (id) {
          await getAction(this.url.findInquiryTemplate, {id: id})
          .then(resp => {
            if (resp.data){
              this.currentTemplate = resp.data[0]
              this.currentTemplate.jsonKeys = JSON.parse(resp.data[0].jsonKeys)
              this.currentTemplate.purchaseKeys = JSON.parse(resp.data[0].purchaseKeys)
              this.currentTemplate.tableColumn = JSON.parse(resp.data[0].tableColumn)
            }
          })
          .catch(()=> {
            this.$message.error('模板查询失败')
          })
        }else {
          this.$message.error('缺失模版,请选择相对于的模版，否则后续无法继续操作')
        }
      },
      loadTemplates() {
        getAction(this.url.findInquiryTemplate)
        .then(resp => {
          resp.data.map(item=> {
            item.tableColumn = JSON.parse(item.tableColumn)
            item.jsonKeys = JSON.parse(item.jsonKeys)
          })
          this.excelTemplates = resp.data
        })
        .catch(()=> {
          this.$message.error('模板查询失败')
        })
      },
      toSearch() {
        if(this.searchForm.proId) {
          this.itemIds = []
          this.currentTemplate = {}
          this.table.loading = true
          getAction(this.url.findItemsByProjectId, {
                  projectId: this.searchForm.proId,
                  pageNum: this.table.pagination.current,
                  pageSize: this.table.pagination.pageSize})
          .then(async resp => {
            if (resp.data.records.length > 0) {
              this.table.pagination.current = parseInt(resp.data.current)
              this.table.pagination.pageSize = parseInt(resp.data.size)
              this.table.pagination.total = parseInt(resp.data.total)
              //解析模板id
              this.currentTemplate.id = resp.data.records[0].templateId
              await this.loadCurrentTemplate(resp.data.records[0].templateId)
            }
            this.table.data = resp.data.records
            //取出所有的itemId(设置模板使用)
            this.table.data.map(item =>{
              this.itemIds.push(item.id)
            })
          }).catch(()=>{
            this.$message.error('查询失败')
          }).finally(()=>{
            this.table.loading = false
          })
        }else {
          this.$message({message: '请选择项目', type: 'warning'})
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .purchase_plan_list {
    /deep/.el-form-item__content{
      height:auto;
      line-height:32px;
      margin-left:90px!important
    }
    .outputlist_upload {
      opacity: 0;
      width: 0;
      overflow: hidden;
    }
    /deep/.el-dialog {
      .el-col {
        padding: 0 4px
      }
    }
  }
</style>
